<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>Fluenty Survey</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
    <!-- PayPal SDK -->
    <script src="https://www.paypal.com/sdk/js?client-id=AfxzMB2clS7_5CdnSEdFBTb3qk9z-64IMFM6kMHl4vXR9W3AlhirzJhf7lNQC2cPb9-EIK5HHfj9AZW8&currency=USD&components=buttons&disable-funding=credit,card,venmo,sofort&locale=en_US"></script>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
      }
      body {
        background-color: #fff;
        color: #0f4c81;
        min-height: 100vh;
        max-width: 600px;
        margin: 0 auto;
        padding: 16px;
      }
      .container {
        display: flex;
        flex-direction: column;
        gap: 16px;
      }

      /* Header */
      .header {
        text-align: center;
        margin-bottom: 8px;
      }
      .product-title {
        font-size: 24px;
        font-weight: 700;
        color: #3ba0ff;
        margin-bottom: 12px;
      }
      .main-title {
        font-size: 28px;
        font-weight: 700;
        color: #0f4c81;
        margin-bottom: 8px;
      }
      .subtitle {
        font-size: 18px;
        color: #0f4c81;
        text-align: center;
        margin-bottom: 16px;
      }

      /* Features */
      .features {
        display: flex;
        flex-direction: column;
        gap: 12px;
        margin-bottom: 16px;
      }
      .feature {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 16px;
        font-weight: 600;
        color: #0f4c81;
      }
      .emoji {
        font-size: 20px;
        min-width: 28px;
        text-align: center;
      }

      /* Pricing Plans */
      .pricing-card {
        border: 1px solid #dce6f9;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 12px;
        position: relative;
        background-color: #fff;
        overflow: hidden;
        cursor: pointer;
        transition: all 0.2s ease;
      }
      .pricing-card.highlighted {
        background-color: #ebf5ff;
      }
      .pricing-card:hover {
        border-color: #3ba0ff;
        box-shadow: 0 4px 12px rgba(59, 160, 255, 0.2);
        transform: translateY(-2px);
      }
      .popular-badge {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        background-color: #3ba0ff;
        color: white;
        text-align: center;
        padding: 6px 0;
        font-weight: 600;
        font-size: 14px;
      }
      .pricing-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 6px;
      }
      .plan-name {
        font-size: 18px;
        font-weight: 700;
      }
      .discount-badge {
        display: inline-block;
        background-color: #ebf5ff;
        color: #0f4c81;
        font-weight: 600;
        padding: 4px 8px;
        border-radius: 16px;
        font-size: 14px;
      }
      .pricing-details {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .price-info {
        display: flex;
        flex-direction: column;
      }
      .original-price {
        color: #999;
        text-decoration: line-through;
        font-size: 16px;
      }
      .final-price {
        color: #555;
        font-size: 16px;
        font-weight: 500;
      }
      .current-price {
        display: flex;
        align-items: flex-start;
      }
      .price-currency {
        font-size: 20px;
        font-weight: 700;
      }
      .price-number {
        font-size: 54px;
        font-weight: 700;
        line-height: 1;
      }
      .price-decimal {
        font-size: 20px;
        font-weight: 700;
        margin-top: 8px;
      }
      .price-period {
        display: block;
        font-size: 14px;
        color: #555;
        margin-top: 2px;
        text-align: center;
      }

      /* PayPal Buttons */
      .paypal-button-container {
        margin-top: 12px;
        width: 100%;
        max-width: 500px;
        margin-left: auto;
        margin-right: auto;
      }

      /* Custom PayPal styling - this will be applied via JS */
      .paypal-button {
        width: 100% !important;
        padding-left: 5px !important;
        padding-right: 5px !important;
      }

      /* Fix PayPal button padding */
      .paypal-button-label-container {
        padding: 0 5px !important;
      }

      /* Security Badge */
      .security-badge {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        color: #4aa181;
        font-size: 14px;
        padding: 6px 12px;
        border: 1px solid #e0e0e0;
        border-radius: 20px;
        margin: 24px auto 12px;
        width: fit-content;
      }

      /* Payment Options */
      .payment-options {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 10px;
        margin-top: 12px;
      }
      .payment-option {
        width: 42px;
        height: 28px;
        border: 1px solid #e0e0e0;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 4px;
      }
      .payment-option img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <!-- Header -->
      <div class="header">
        <h2 class="product-title">Fluenty Pro</h2>
        <h1 class="main-title">Get Unlimited Access</h1>
        <p class="subtitle">Accessible anytime, anywhere for flexible learning.</p>
      </div>

      <!-- Features -->
      <div class="features">
        <div class="feature">
          <span class="emoji">👥</span>
          <span>Unlimited Interactive Practice</span>
        </div>
        <div class="feature">
          <span class="emoji">📝</span>
          <span>Personalized Study Plan</span>
        </div>
        <div class="feature">
          <span class="emoji">💯</span>
          <span>Real-time AI feedback</span>
        </div>
        <div class="feature">
          <span class="emoji">⛳</span>
          <span>Control & Track Your Progress</span>
        </div>
      </div>

      <!-- Weekly Plan -->
      <div class="pricing-card" data-plan="weekly" data-price="7.00" data-plan-name="1 Week">
        <div class="pricing-header">
          <div class="plan-name">1 Week</div>
          <div class="discount-badge">SAVE 60%</div>
        </div>
        <div class="pricing-details">
          <div class="price-info">
            <!-- <div class="original-price">$2.50</div> -->
            <div class="final-price">$7.00</div>
          </div>
          <div class="current-price">
            <span class="price-currency">$</span>
            <span class="price-number">0</span>
            <span class="price-decimal">99</span>
            <span class="price-period">per day</span>
          </div>
        </div>
        <!-- PayPal container for weekly plan -->
        <div id="paypal-button-weekly" class="paypal-button-container"></div>
      </div>

      <!-- Yearly Plan -->
      <div class="pricing-card highlighted" data-plan="yearly" data-price="39.99" data-plan-name="1 Year">
        <div class="popular-badge">MOST POPULAR</div>
        <div class="pricing-header" style="margin-top: 18px">
          <div class="plan-name">1 Year</div>
          <div class="discount-badge">SAVE 60%</div>
        </div>
        <div class="pricing-details">
          <div class="price-info">
            <!-- <div class="original-price">$0.27</div> -->
            <div class="final-price">$39.99</div>
          </div>
          <div class="current-price">
            <span class="price-currency">$</span>
            <span class="price-number">0</span>
            <span class="price-decimal">09</span>
            <span class="price-period">per day</span>
          </div>
        </div>
        <!-- PayPal container for yearly plan -->
        <div id="paypal-button-yearly" class="paypal-button-container"></div>
      </div>

      <!-- Security Badge -->
      <div class="security-badge">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M9 12L11 14L15 10M21 12C21 16.9706 16.9706 21 12 21C7.02944 21 3 16.9706 3 12C3 7.02944 7.02944 3 12 3C16.9706 3 21 7.02944 21 12Z"
            stroke="#4aa181"
            stroke-width="2"
            stroke-linecap="round"
            stroke-linejoin="round"
          />
        </svg>
        <span>Pay safe & secure</span>
      </div>

      <!-- Payment Options -->
      <div class="payment-options">
        <div class="payment-option">
          <img src="https://cdn-icons-png.flaticon.com/512/174/174861.png" alt="PayPal" />
        </div>
        <div class="payment-option">
          <img src="https://cdn-icons-png.flaticon.com/512/349/349221.png" alt="Apple Pay" />
        </div>
        <div class="payment-option">
          <img src="https://cdn-icons-png.flaticon.com/512/888/888870.png" alt="Google Pay" />
        </div>
        <div class="payment-option">
          <img src="https://cdn-icons-png.flaticon.com/512/349/349230.png" alt="Visa" />
        </div>
        <div class="payment-option">
          <img src="https://cdn-icons-png.flaticon.com/512/349/349228.png" alt="MasterCard" />
        </div>
        <div class="payment-option">
          <img src="https://cdn-icons-png.flaticon.com/512/349/349247.png" alt="Maestro" />
        </div>
        <div class="payment-option">
          <img src="https://cdn-icons-png.flaticon.com/512/349/349224.png" alt="Discover" />
        </div>
        <div class="payment-option">
          <img src="https://cdn-icons-png.flaticon.com/512/349/349226.png" alt="American Express" />
        </div>
      </div>
    </div>

    <script>
      // 全局变量
      window.isProcessingWeekly = false
      window.isProcessingYearly = false
      window.productsData = null
      window.weeklyPlanCode = ''
      window.yearlyPlanCode = ''
      window.isDataLoaded = false

      // 单例模式，确保只加载一次数据
      window.loadProductsOnce = async function () {
        if (window.isDataLoaded || window.productsData) {
          console.log('产品数据已加载，跳过重复请求')
          return window.productsData
        }

        try {
          console.log('开始加载产品数据')
          const module = await import('/pay/service.ts')
          window.PaymentService = module.PaymentService

          window.isDataLoaded = true // 标记加载状态
          const data = await window.PaymentService.getAllProducts()
          window.productsData = data
          console.log('产品数据加载成功:', data)

          // 保存产品代码
          if (data && data.length >= 2) {
            window.weeklyPlanCode = data[0].code
            window.yearlyPlanCode = data[1].code
          }

          // 更新界面显示
          updateProductDisplay(data)

          return data
        } catch (error) {
          console.error('获取产品数据失败:', error)
          window.isDataLoaded = false // 重置加载状态以便重试
          return null
        }
      }

      // 防止重复创建订单
      window.createPayPalOrderSafe = (function () {
        const processingOrders = new Map()

        return async function (planCode, defaultValue, isWeekly = true) {
          const orderKey = isWeekly ? 'weekly' : 'yearly'

          // 如果已经有相同的订单正在处理中，返回存储的Promise
          if (processingOrders.has(orderKey)) {
            console.log('已有相同订单正在处理中，复用现有请求')
            return processingOrders.get(orderKey)
          }

          // 创建新订单并存储Promise
          console.log('开始创建新的PayPal订单:', planCode)
          const orderPromise = new Promise(async (resolve, reject) => {
            try {
              // 确保产品数据已加载
              if (!window.productsData) {
                await window.loadProductsOnce()
              }

              // 获取最新的计划代码
              const finalPlanCode = isWeekly ? window.weeklyPlanCode || planCode : window.yearlyPlanCode || planCode

              // 调用API创建订单
              const res = await window.PaymentService.createPayPalSubscription({
                priceId: finalPlanCode,
              })

              if (res && res.paypalOrderId) {
                console.log('订单创建成功:', res.paypalOrderId)
                resolve(res.paypalOrderId)
              } else {
                reject(new Error('No order ID returned'))
              }
            } catch (error) {
              console.error('订单创建失败:', error)
              reject(error)
            } finally {
              // 订单处理完成后，从Map中移除
              setTimeout(() => {
                processingOrders.delete(orderKey)
              }, 1000)
            }
          })

          // 存储Promise以便复用
          processingOrders.set(orderKey, orderPromise)
          return orderPromise
        }
      })()

      // 页面加载完成后执行
      document.addEventListener('DOMContentLoaded', function () {
        // 加载产品数据
        window.loadProductsOnce()
      })

      // 更新产品显示
      function updateProductDisplay(products) {
        if (!products || products.length === 0) return

        // 根据产品数据更新页面显示
        products.forEach((product, index) => {
          if (index === 0 && product) {
            // 更新周计划显示
            updatePlanDisplay('.pricing-card[data-plan="weekly"]', product)
          } else if (index === 1 && product) {
            // 更新年计划显示
            updatePlanDisplay('.pricing-card[data-plan="yearly"]', product)
          }
        })
      }

      // 更新单个计划的显示
      function updatePlanDisplay(selector, product) {
        const card = document.querySelector(selector)
        if (!card) return

        // 更新价格等信息
        if (product.price) {
          const finalPrice = card.querySelector('.final-price')
          if (finalPrice) finalPrice.textContent = '$' + product.price
        }

        // 可以更新其他产品信息
        if (product.name) {
          const planName = card.querySelector('.plan-name')
          if (planName) planName.textContent = product.name
        }
      }
    </script>

    <script type="module">
      // 页面加载完成后初始化PayPal按钮
      document.addEventListener('DOMContentLoaded', function () {
        // 初始化PayPal按钮
        initPayPalButtons()
      })

      // 初始化PayPal按钮
      function initPayPalButtons() {
        if (!window.paypal) {
          console.error('PayPal SDK未加载')
          return
        }

        // Weekly plan PayPal button
        paypal
          .Buttons({
            style: {
              layout: 'horizontal',
              color: 'blue',
              shape: 'rect',
              label: 'pay',
              tagline: false,
              height: 50,
            },
            fundingSource: paypal.FUNDING.PAYPAL,
            createOrder: async function (data, actions) {
              try {
                // 使用安全的创建订单函数
                return await window.createPayPalOrderSafe('weekly_plan', '7.00', true)
              } catch (error) {
                console.log('订单创建失败，使用前端创建:', error)
                // 前端创建订单作为后备方案
                return actions.order.create({
                  purchase_units: [
                    {
                      amount: {
                        value: '7.00',
                      },
                      description: 'Fluenty Pro - 1 Week Subscription',
                    },
                  ],
                })
              }
            },
            onApprove: function (data, actions) {
              return actions.order.capture().then(function (details) {
                console.log('交易完成:', details)
                alert('Transaction completed by ' + details.payer.name.given_name)
              })
            },
            onError: function (err) {
              console.error('PayPal错误:', err)
              alert('Payment Error, please try again')
            },
          })
          .render('#paypal-button-weekly')

        // Yearly plan PayPal button
        paypal
          .Buttons({
            style: {
              layout: 'horizontal',
              color: 'blue',
              shape: 'rect',
              label: 'pay',
              tagline: false,
              height: 50,
            },
            fundingSource: paypal.FUNDING.PAYPAL,
            createOrder: async function (data, actions) {
              try {
                // 使用安全的创建订单函数
                return await window.createPayPalOrderSafe('yearly_plan', '39.99', false)
              } catch (error) {
                console.log('订单创建失败，使用前端创建:', error)
                // 前端创建订单作为后备方案
                return actions.order.create({
                  purchase_units: [
                    {
                      amount: {
                        value: '39.99',
                      },
                      description: 'Fluenty Pro - 1 Year Subscription',
                    },
                  ],
                })
              }
            },
            onApprove: function (data, actions) {
              return actions.order.capture().then(function (details) {
                alert('Transaction completed by ' + details.payer.name.given_name)
              })
            },
            onError: function (err) {
              console.error('PayPal错误:', err)
              alert('Payment Error, please try again')
            },
          })
          .render('#paypal-button-yearly')

        // 调整PayPal按钮样式
        setTimeout(function () {
          const buttonTexts = document.querySelectorAll('.paypal-button-text, .paypal-button-label-container')
          buttonTexts.forEach(text => {
            text.textContent = 'PayPal Buy Now'
            text.style.fontSize = '16px'
            text.style.fontWeight = '600'
          })

          const buttonContainers = document.querySelectorAll('.paypal-button')
          buttonContainers.forEach(button => {
            button.style.minWidth = '300px'
            button.style.paddingLeft = '5px'
            button.style.paddingRight = '5px'
          })
        }, 1000)
      }
    </script>
  </body>
</html>
